package tushare

import (
	"bytes"
	"encoding/json"

	"io/ioutil"
	"net/http"

	"tushare/conf"
	"tushare/model"
)

type resposeJson struct {
	RequestId string      `json:"request_id"`
	Code      int         `json:"code"`
	Data      resposeData `json:"data"`
}

type resposeData struct {
	Items [][]string `json:"items"`
}

func StockBasic() {
	data := make(map[string]interface{})
	data["api_name"] = "stock_basic"
	data["token"] = conf.GetToken()
	data["fields"] = "ts_code,symbol,name,area,industry,fullname,enname,cnspell,market,exchange,curr_type,list_status,list_date,delist_date,is_hs"

	bytesData, _ := json.Marshal(data)
	resp, _ := http.Post("http://api.waditu.com", "application/json", bytes.NewReader(bytesData))
	body, _ := ioutil.ReadAll(resp.Body)

	jsonStrByte := []byte(body)
	decodeData := resposeJson{}
	json.Unmarshal(jsonStrByte, &decodeData)

	for _, v := range decodeData.Data.Items {
		ts := model.TushareStock{}
		ts.TsCode = v[0]
		ts.Symbol = v[1]
		ts.Name = v[2]
		ts.Area = v[3]
		ts.Industry = v[4]
		ts.Fullname = v[5]
		ts.Enname = v[6]
		ts.Cnspell = v[7]
		ts.Market = v[8]
		ts.Exchange = v[9]
		ts.CurrType = v[10]
		ts.ListStatus = v[11]
		ts.ListDate = v[12]
		ts.DelistDate = v[13]
		ts.IsHs = v[14]
		ts.Collect = "0"
		ts.PeakButton = "0"
		ts.PeakCenter = "0"
		ts.PeakStable = "0"
		info := model.StockInfoByTsCode(ts.TsCode)
		if info.TsCode != "" {
			continue
		}
		model.StockCreate(ts)
	}

}

func GetStockList() []model.TushareStock {
	return model.StockList()
}
